package com.example.criminalintent.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TimePicker;

import com.example.criminalintent.R;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

public class TimePickerFragment extends DialogFragment {

    private static String timeTag = "com.example.time";
    public static String EXTRA_TIME = "extra_time";
    private TimePicker mTimePicker;
    public static TimePickerFragment newInstance(Date crimeDate){
        TimePickerFragment timePickerFragment = new TimePickerFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(timeTag,crimeDate);
        timePickerFragment.setArguments(bundle);
        return timePickerFragment;

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_time,null);
        mTimePicker = view.findViewById(R.id.time_picker);
        mTimePicker.setIs24HourView(true);
        Date currentDate = (Date) getArguments().getSerializable(timeTag);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        mTimePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY));
        mTimePicker.setMinute(calendar.get(Calendar.MINUTE));

        return new AlertDialog.Builder(getActivity()).setTitle("Pick Time")
                .setView(view)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int hour =  mTimePicker.getHour();
                        int minute = mTimePicker.getMinute();

                        sendResult(Activity.RESULT_OK,hour,minute);
                    }
                })
                .create();
    }


    private void sendResult(int resultCode,int hour,int minute){
        if(getTargetFragment() == null){
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(EXTRA_TIME,String.valueOf(hour+"+"+minute));
        getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
    }
}
